package com.ken.common.core.utils;

import org.springframework.beans.BeanUtils;

import java.util.Collection;
import java.util.Objects;
import java.util.Optional;

/**
 * 对象复制
 */
public class BeanCopyUtils {

    /**
     * 全复制对象
     */
    public static <T> T copyBean(Object from, Class<T> to){
        T toObj = Optional.ofNullable(from)
                .map(fromObj -> {
                    String json = JsonUtils.obj2Json(from);
                    return JsonUtils.json2Obj(json, to);
                }).orElse(null);
        return toObj;
    }

    /**
     * 复制集合
     * @param collection1
     * @param collection2
     * @param classObj
     * @param <T>
     */
    public static <T> void copyList(Collection collection1, Collection collection2, Class<T> classObj) {
        if ((!Objects.isNull(collection1)) && (!Objects.isNull(collection2))) {
            for (Object object : collection1) {
                try {
                    //创建复制对象
                    T item = classObj.newInstance();
                    BeanUtils.copyProperties(object, item);
                    collection2.add(item);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
